# coding: utf-8
'''
Description: 
version: 1.0.0
Author: peng2.zhang
Date: 2021-05-10 17:24:32
LastEditors: peng2.zhang
LastEditTime: 2022-01-19 18:12:33
'''

import sqlalchemy
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
from datetime import datetime, date
from ci_conclude.log import logger

HOSTNAME = "10.43.43.137"
PORT = 3306
DATABASE = "autorunner"
USERNAME = "autorunner"
PASSWORD = "autorunner"

db_url = f'mysql+pymysql://{USERNAME}:{PASSWORD}@{HOSTNAME}:{PORT}/{DATABASE}?charset=utf8&autocommit=true'

engine = create_engine(db_url)

Base = declarative_base(bind=engine)

DBSession = sessionmaker(engine)
# dbsession = DBSession()

class DBase(object):

    @classmethod
    def _get_keys(cls):
        return sqlalchemy.orm.class_mapper(cls).c.keys()
    
    @classmethod
    def filter_kwargs(cls, kwargs):
        keys = cls._get_keys()
        filtered_kwargs = {}
        for k, v in kwargs.items():
            if k in keys:
                filtered_kwargs.update({k: v})
        return filtered_kwargs

    def get_dict(self):
        d = {}
        for k in self._get_keys():
            d[k] = getattr(self, k)
        return d
    
    def as_dict(self):
        d = self.get_dict()
        for k,v in d.items():
            if isinstance(v, date):
                d[k] = v.strftime("%Y-%m-%d")
                # logger.info(f"date {k}: {d[k]}")
            if isinstance(v, datetime):
                d[k] = v.strftime("%Y-%m-%d %H:%M:%S")
                # logger.info(f"datetime {k}: {d[k]}")
        return d


class DBConnection:

    def __init__(self):
        self.db = DBSession()

    def __enter__(self):
        logger.info(f"__enter__")
        return self

    def __exit__(self, except_type, except_value, except_trace):
        logger.info(f"__exit__")
        # logger.info(f"type: {except_type}")
        # logger.info(f"value: {except_value}")
        # logger.info(f"trace: {except_trace}")
        self.db.close()
